//
//  CarFindHistory.m
//  Car
//
//  Created by 何晓文 on 15/10/7.
//  Copyright (c) 2015年 朱鸿儒. All rights reserved.
//

#import "CarFindHistory.h"

@implementation CarFindHistory
static CarFindHistory *carFindHistory;
static FMDatabase *_carFindHistoryDB;

+ (CarFindHistory *)shareHistory {
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		if (carFindHistory == nil) {
			carFindHistory = [[CarFindHistory alloc]init];
		}
	});
	return carFindHistory;

}

- (NSString *)getSqlitePathWithUser:(NSString *)user {
	
	//获取document路径
	NSString *docPath = [NSSearchPathForDirectoriesInDomains(9, 9, 1) lastObject];
	//拼接文件路径
	NSString *filePath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@carFindHistory.sqlite", user]];
	NSLog(@"%@", filePath);
	return filePath;
}
/**
 *添加收藏
 */
- (void)addCarFindHistoryModel:(UsedCarModel *)model WithUser:(NSString *)user {
	
	//创建数据库文件
	_carFindHistoryDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	//链接数据库
	[_carFindHistoryDB open];
	NSString *slq = [NSString stringWithFormat:@"create table if not exists History (id integer primary key,name TEXT,CarID integer UNIQUE,imageurl TEXT,price TEXT,buytime TEXT, dealaddr TEXT,mileage TEXT);"];

	
	
	//创建表
	[_carFindHistoryDB executeUpdate:slq];
	
	//插入数据
	BOOL done = [_carFindHistoryDB executeUpdateWithFormat:@"insert into History (name,CarID,imageurl,price, buytime, dealaddr,mileage) values (%@,%@,%@,%@,%@,%@,%@);",model.name, model.ID, model.imgurl, model.price, model.buytime, model.dealaddr,model.mileage];
	if (done) {
		
	}else {
		
	}
	
}
- (void)deleteCarFindHistoryWithUser:(NSString *)user {
	_carFindHistoryDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	[_carFindHistoryDB open];
	NSString *slq = [NSString stringWithFormat:@"delete from History"];
	BOOL result = [_carFindHistoryDB executeUpdate:slq];
	if (result) {
		[ProgressHUD showSuccess:@"删除成功"];
	}else {
		[ProgressHUD showError:@"删除失败"];
	}
	
}


- (NSMutableArray *)extractDataWithUser:(NSString *)user {
	NSMutableArray *array = [NSMutableArray array];
	
	_carFindHistoryDB = [FMDatabase databaseWithPath:[self getSqlitePathWithUser:user]];
	[_carFindHistoryDB open];
	
	//查询所有音乐收藏数据
	NSString *sql = [NSString stringWithFormat:@"select * from History ORDER BY ID DESC LIMIT 30"];
	FMResultSet *set = [_carFindHistoryDB executeQuery:sql];
	while (set.next) {
		//将数据库中的blob转化为data
		
		//初始化model接收
		UsedCarModel *model = [[UsedCarModel alloc] init];
		model.name = [set objectForColumnName:@"name"];
		model.price = [set objectForColumnName:@"price"];
		model.imgurl = [set objectForColumnName:@"imageurl"];
		model.ID = [set objectForColumnName:@"CarID"];
		model.buytime = [set objectForColumnName:@"buytime"];
		model.dealaddr = [set objectForColumnName:@"dealaddr"];
		model.mileage = [set objectForColumnName:@"mileage"];
		NSLog(@"%@",model.name);
		[array addObject:model];
	}
	
	return array;
	
}
@end
